/*
 * ----------------------------------------------------------------------------
 *
 *   Google Gadgets Flickr Photos
 *
 *  Copyright (c) 2006, Tennetiss
 *  http://www.akaiho.com/
 *
 *
 *  CHANGELOG:
 *    2006-08-06  :  initially setup
 *    2006-10-27  :  able to jump to the web page of each photo
 *    2006-11-21  :  can handle multiple tags
 *    2007-06-07  :  can have upto 500 pictures per tag. (Thanks James Kasyan!!)
 *    2007-10-06  :  fixed the bug consuming memory. (Thanks again, James Kasyan!!)
 *
 * ----------------------------------------------------------------------------
 */

var kCurrentVersion = "1.21";
var kflickrXmlUrl = "http://www.flickr.com/services/rest/?method=flickr.photos.search&format=rest&api_key=3aba8184848f9263b80795c95529bcd1&per_page=500&tags={tagname}";
var kflickrUrl = "http://www.flickr.com/photos/tags/{tagname}/";
var tag = new Array();

var kCheckIntervalMs; // refresh rate.
var kRotationIntervalMs;

var timerId = null;   // time interval id
var timerId2 = null;

var tagindex;
var fetchindex;

var imageArray = new Array();
var imageIndex = 0;

var titleArray = new Array();
var linkArray  = new Array();
var photouriArray = new Array();

function Main() {
  SetDefaultOptions();
  pluginHelper.onAddCustomMenuItems = AddCustomMenuItems;
  pluginHelper.onShowOptionsDlg = ShowOptionsDlg;
  var tmptag = options("tag");
  tag = tmptag.split(" ");
  ResetObtainInterval(options("obtaininterval"));
  ResetRotationInterval(options("rotationinterval"));
  RefreshDisplay();
}

function SetDefaultOptions() {
  options.defaultValue("obtaininterval") = "10";
  options.defaultValue("rotationinterval") = "1";
  options.defaultValue("tag") = "art";
}

function view_onopen()
{
  Main();
}

function ResetObtainInterval(newIntervalmin){
  kCheckIntervalMs = 1000 * 60 * newIntervalmin;
  if(timerId != null) { view.clearInterval(timerId); }
  timerId = view.setInterval("RefreshDisplay()", kCheckIntervalMs);
}

function ResetRotationInterval(newIntervalmin){
  kRotationIntervalMs = 1000 * 60 * newIntervalmin;
  if(timerId2 != null) { view.clearInterval(timerId2); }
  timerId2 = view.setInterval("RedrawImage()", kRotationIntervalMs);
}

function OnOpenItem(item) {
  var wshShell = new ActiveXObject("WScript.Shell");
  var url = kflickrUrl.replace(/\{tagname\}/g, options.GetValue("tag"));
  wshShell.run(url);
  wshShell = null;
}

function AddCustomMenuItems(menu) {
  menu.AddItem("Refresh", 0, RefreshDisplay);
  menu.AddItem("Redraw", 0, RedrawImage);
}

function RefreshDisplay() {
  for( var i=0; i < photouriArray.length; i++){
    titleArray[i] = null;
    linkArray[i] = null;
    photouriArray[i] = null;
  }
  titleArray.splice( 0, titleArray.length );
  linkArray.splice( 0, linkArray.length );
  photouriArray.splice( 0, photouriArray.length );
  imageIndex = 0;
  for( var i=0; i<tag.length; i++){
    FetchFeed(i);
  }
}

function FetchFeed( index ) {
  var url = kflickrXmlUrl.replace(/\{tagname\}/g, tag[index]);
  var http = new XMLHttpRequest();
  http.onreadystatechange = OnReceivedData;
  http.open("GET",  url, true);
  // do this, or it keeps reading cache
  http.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");     
  try {
    http.send();
  }
  catch(e) {
  }
  function OnReceivedData() {
    if (http && http.readyState == 4) { // completed OK?
      var doc = new DOMDocument();
      doc.loadXML(http.responseText);
      var photo_m, photo_url, title, link, farm, server, photo_id, secret, owner;
      var elem = doc.getElementsByTagName("photo");
      if (elem != null && elem.length > 0) {
        for(var i = 0; i < elem.length; ++i) {
          title = elem[i].attributes.getNamedItem("title").value;
          farm = elem[i].attributes.getNamedItem("farm").value;
          server = elem[i].attributes.getNamedItem("server").value;
          secret = elem[i].attributes.getNamedItem("secret").value;
          photo_id = elem[i].attributes.getNamedItem("id").value;
          owner = elem[i].attributes.getNamedItem("owner").value;
          link = "http://www.flickr.com/photos/" + owner + "/" + photo_id;
          photo_url = "http://farm" + farm + ".static.flickr.com/" + server + "/" + photo_id + "_" + secret + "_m.jpg";
          titleArray.push(title);
          linkArray.push(link);
          photouriArray.push(photo_url);
        }
      }
      http = null;
    }
    RedrawImage();
  }
}

function getImage() {
  imageArray = null;
  imageArray = new Array();
  var http2 = null;
  http2 = new XMLHttpRequest();
  http2.onreadystatechange = OnReceivedPhoto;
  fetchindex = Math.floor(Math.random()*(photouriArray.length-1))
  http2.open("GET",  photouriArray[fetchindex], false);
  try {
    http2.send();
  }
  catch(e) {
  }
  //alert(photouriArray[fetchindex]);
  function OnReceivedPhoto() {
    if (http2 && http2.readyState == 4) { // completed OK?
      var source = http2.responseStream;
      graphic.src = source;
    }
  }
}

function loadRelative() {
  var wshShell = new ActiveXObject("WScript.Shell");
  wshShell.run(linkArray[fetchindex]);
  wshShell = null;
}

function RedrawImage() {
  if(photouriArray.length >= 1){
    getImage();
    graphic.visible = true;
  }
  else{
    graphic.visible = false;
  }
}

// ---- Options Dialog ----
function ShowOptionsDlg(wnd) {

//  wnd.AddControl(gddWndCtrlClassLabel, 0, "", ENTER,
//      30, 10, 200, 15);
  wnd.AddControl(gddWndCtrlClassLabel, 0, "", ENTER_TAG,
      30, 10, 200, 15);
  wnd.AddControl(gddWndCtrlClassEdit, 0, "tag", options("tag"),
      30, 25, 150, 22);

  wnd.AddControl(gddWndCtrlClassLabel, 0, "", ENTER_OBTAIN_INTERVAL,
                 30, 50, 200, 15);
  wnd.AddControl(gddWndCtrlClassEdit, 0, "obtaininterval", options("obtaininterval"),
                 30, 65, 150, 22);

  wnd.AddControl(gddWndCtrlClassLabel, 0, "", ENTER_ROTATION_INTERVAL,
                 30,  90, 200, 15);
  wnd.AddControl(gddWndCtrlClassEdit, 0, "rotationinterval", options("rotationinterval"),
                 30, 105, 150, 22);

  wnd.onClose = OptionsDlgClosed;
}


function OptionsDlgClosed(wnd, code) {
  if (code == gddIdOK) {
    var tagname = wnd.GetControl("tag");
    options("tag") = tagname.text;
    tag = tagname.text.split(" ");

    var obtaininterval = wnd.GetControl("obtaininterval");
    if( isNaN(obtaininterval.text) || (obtaininterval.text <= 0) ){
      alert( inputTimeError );
    }
    else {
      options("obtaininterval") = obtaininterval.text;
      ResetObtainInterval(obtaininterval.text);
    }

    var rotationinterval = wnd.GetControl("rotationinterval");
    if( isNaN(rotationinterval.text) || (rotationinterval.text <= 0) ){
      alert( inputTimeError );
    }
    else {
      options("rotationinterval") = rotationinterval.text;
      ResetRotationInterval(rotationinterval.text);
    }
    RefreshDisplay();
  }
}


